package com.example.model_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.model_service.dto.QueryDTO;
import com.example.model_service.service.ObjInfoService;
import com.example.model_service.domain.ObjInfo;
import com.example.model_service.mapper.ObjInfoMapper;
import com.example.model_service.utils.MinioUtil;
import com.example.model_service.vo.OptionVO;
import com.example.model_service.vo.QueryVO;
import com.example.model_service.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ObjInfoServiceImpl extends ServiceImpl<ObjInfoMapper, ObjInfo>
    implements ObjInfoService {

    @Resource
    private ObjInfoMapper objInfoMapper;

    @Resource
    private MinioUtil minioUtil;

    @Override
    public Result queryModels(QueryDTO queryDTO) {
        IPage<ObjInfo> iPage = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        LambdaQueryWrapper<ObjInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjInfo::getUserId, queryDTO.getUserId());
        IPage<ObjInfo> page = objInfoMapper.selectPage(iPage, wrapper);
        QueryVO<ObjInfo> vo = new QueryVO<>();
        vo.setList(page.getRecords());
        vo.setTotal(page.getTotal());
        return Result.success(vo).message("查询成功");
    }

    @Override
    public Result uploadModel(MultipartFile file, Integer userId) {
        if(file.getSize() > 250*1024*1024) {
            return Result.fail().message("模型大小不能超过250MB");
        }

        // 获取文件初始名称（model_cli）
        String originalFilename = file.getOriginalFilename();
        if(!originalFilename.contains(".obj")){
            return Result.fail().message("文件格式有误，仅支持.obj文件");
        }

        LambdaQueryWrapper<ObjInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjInfo::getUserId, userId)
                .eq(ObjInfo::getModelCli, originalFilename);
        if (objInfoMapper.selectOne(wrapper)!=null) {
            return Result.fail().message("当前模型文件已经存在，请重新上传");
        }

        //获取文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //重新生成文件名字（model_ser）
        String model_ser =  UUID.randomUUID()+ "_" + userId + suffixName ;


        try {
            minioUtil.putObject(file, model_ser);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail().message("文件上传失败");
        }

        ObjInfo info = new ObjInfo();
        info.setModelCli(originalFilename);
        info.setModelSer(model_ser);
        System.out.println(model_ser);
        info.setUploadTime(LocalDateTime.now());
        info.setUserId(userId);
        save(info);

        return Result.success().message("文件上传成功");
    }

    @Override
    public ResponseEntity<byte[]> downloadModel(Integer id, HttpServletResponse response) {
        ObjInfo info = getById(id);
        if(info!=null) {
            try {
                return minioUtil.download(info.getModelCli(), info.getModelSer(), response);
            } catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
        return null;
    }

    @Override
    public Result removeModel(Integer id) {
        ObjInfo info = getById(id);
        if(info==null) {
            return Result.fail().message("模型信息不存在");
        }
        try {
            minioUtil.removeObject("obj-model", info.getModelSer());
            removeById(id);
        }catch (Exception e) {
            e.printStackTrace();
            return Result.fail().message("模型文件删除失败");
        }
        return Result.success().message("模型删除成功");
    }

    @Override
    public Result queryAllModels(Integer userId) {
        LambdaQueryWrapper<ObjInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjInfo::getUserId, userId);
        List<ObjInfo> objInfos = objInfoMapper.selectList(wrapper);
        List<OptionVO> list = new ArrayList<>();
        for (ObjInfo objInfo : objInfos) {
            OptionVO vo = new OptionVO();
            vo.setLabel(objInfo.getModelCli());
            vo.setValue("http://119.29.191.232:9000/obj-manager/"+objInfo.getModelSer());
            list.add(vo);
        }
        return Result.success(list).message("查询成功");
    }
}




